<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="账户">
                <a-input allow-clear placeholder="请输入账户" v-model="queryParam.user_name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="昵称">
                <a-input allow-clear placeholder="请输入昵称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号">
                <div class="select">
                  <a-input allow-clear placeholder="请输入手机号" v-model="queryParam.mobile"></a-input>
                  <a-button type="primary" @click="$refs.table.refresh(1)">查询</a-button>
                </div>
              </a-form-item>
            </a-col>
            <!-- <a-col :md="8" :sm="24">
              <a-form-item label="代理类型">
                <a-select v-model="queryParam.area_level">
                  <a-select-option value="-1"> 全部 </a-select-option>
                  <a-select-option value="0"> 默认 </a-select-option>
                  <a-select-option value="3"> 省 </a-select-option>
                  <a-select-option value="2"> 市 </a-select-option>
                  <a-select-option value="1"> 区 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="$refs.table.refresh(1)">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="0"> 已禁用 </a-radio-button>
          <a-radio-button value="1"> 已启用 </a-radio-button>
        </a-radio-group>
        <div>
          <a-button type="primary" @click="visibleCreate = true" icon="plus">新建</a-button>
          <!-- <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="allStatus(1)">批量通过</a-menu-item>
              <a-menu-item @click="allStatus(3)">批量拒绝</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown> -->
        </div>
      </div>
      <s-table rowKey="id" size="default" :columns="columns" :data="loadData" ref="table">
        <span slot="expire_time" slot-scope="text"
          ><span v-if="text == 0">永久</span><span v-else>{{ text | timeFormat('YYYY-MM-DD') }}</span></span
        >
        <div slot="status" slot-scope="scope">
          <div class="status">
            <span :class="scope == 0 ? 'disabled' : 'open'"></span>
            <span>{{ scope == 0 ? '已禁用' : '已启用' }}</span>
          </div>
        </div>
        <div slot="area_level" slot-scope="scope">
          <div class="status">
            <!--            <span :class="scope == 0 ? 'disabled' : 'open'"></span>-->
            <span>{{ area_level(scope) }}</span>
          </div>
        </div>
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="onInStore(record)" size="small">进入</a-button>
          <a-divider type="vertical" style="margin: 0 1px" />
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" style="margin: 0 1px" />
          <a-dropdown>
            <a-button type="link" size="small"> 更多 <a-icon type="down" /></a-button>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-button type="link" size="small" @click="onEditPassword(record)">修改密码</a-button>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm
                  title="确认删除账户吗？"
                  :disabled="record.username == 'admin'"
                  @confirm="handleDelete(record)"
                >
                  <a-button type="link" size="small" :disabled="record.username == 'admin'">删除</a-button>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-if="record.username != 'admin'">
                <a-popconfirm
                  title="确认开启吗？"
                  @confirm="changeStatus(record, '1')"
                  :disabled="record.is_enable == 1"
                >
                  <a-button type="link" size="small" :disabled="record.is_enable == 1">开启</a-button>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-if="record.username != 'admin'">
                <a-popconfirm
                  title="确认禁用吗？"
                  @confirm="changeStatus(record, '0')"
                  :disabled="record.is_enable == 0"
                >
                  <a-button type="link" size="small" :disabled="record.is_enable == 0">禁用</a-button>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </s-table>
    </a-card>
    <a-modal v-model="visibleEditPassword" title="修改密码" :confirmLoading="confirmLoading" @ok="onEditPasswordOk">
      <a-input placeholder="请输入新密码" v-model="newPassword" />
    </a-modal>
    <a-modal
      v-model="visibleCreate"
      :title="!formModel.id ? '创建账户' : '修改账户'"
      :confirmLoading="confirmLoading"
      @ok="onCreateOk"
      :afterClose="closeModal"
    >
      <a-form-model ref="modelForm" :model="formModel" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="账户名" has-feedback prop="username">
          <a-input v-model="formModel.username" :disabled="formModel.username == 'admin'" placeholder="请输入账户名" />
        </a-form-model-item>
        <a-form-model-item label="是否开启" has-feedback prop="is_enable">
          <a-radio-group v-model="formModel.is_enable" :disabled="formModel.username == 'admin'">
            <a-radio value="1"> 开启 </a-radio>
            <a-radio value="0"> 关闭 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="密码" v-if="!formModel.id" has-feedback prop="password">
          <a-input v-model="formModel.password" placeholder="请输入密码" />
        </a-form-model-item>
        <a-form-model-item label="手机号" has-feedback prop="mobile">
          <a-input v-model="formModel.mobile" placeholder="请输入手机号" />
        </a-form-model-item>
        <a-form-model-item label="昵称" has-feedback prop="name">
          <a-input v-model="formModel.name" placeholder="请输入昵称" />
        </a-form-model-item>
        <a-form-model-item label="绑定用户" has-feedback prop="saas_user_id">
          <div style="display: flex">
            <a-input v-model="saas_user_name" disabled />
            <a-button type="primary" @click="visible = true" style="margin-left: 15px">选择</a-button>
          </div>
        </a-form-model-item>
        <a-form-model-item label="可创建商城数量">
          <a-input-number v-model="formModel.max_app_count" :min="0" :max="9999" style="width: 100%" />
        </a-form-model-item>
        <a-form-model-item label="地区" prop="area">
          <Address v-model="formModel.area"></Address>
        </a-form-model-item>
        <!-- <a-form-model-item label="区域代理等级">
          <a-select v-model="formModel.area_level" placeholder="请选择区域代理等级">
            <a-select-option value="0"> 默认 </a-select-option>
            <a-select-option value="3"> 省 </a-select-option>
            <a-select-option value="2"> 市 </a-select-option>
            <a-select-option value="1"> 区 </a-select-option>
          </a-select>
        </a-form-model-item> -->
        <!-- <a-form-model-item label="最大让利比例（%）" v-if="formModel.username != 'admin'">
          <a-input-number v-model="formModel.max_price" :min="0.0" :max="9999" precision="2" style="width: 100%" />
        </a-form-model-item> -->
        <!-- <a-form-model-item label="提现服务费率（%）" v-if="formModel.username != 'admin'">
          <a-input-number v-model="formModel.rate" :min="0.0" :max="9999" precision="2" style="width: 100%" />
        </a-form-model-item> -->
        <a-form-model-item label="有效期" v-if="formModel.username != 'admin'">
          <a-radio-group v-model="formModel.expire_time_always">
            <a-radio :value="true"> 永久 </a-radio>
            <a-radio :value="false"> 选择时间 </a-radio>
          </a-radio-group>
          <a-date-picker
            v-model="formModel.expire_time"
            format="YYYY-MM-DD"
            style="width: 100%; margin-top: 5px"
            v-if="!formModel.expire_time_always"
          />
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea v-model="formModel.remark" placeholder="请输入备注" :auto-size="{ minRows: 3, maxRows: 5 }" />
        </a-form-model-item>
        <a-form-model-item label="详细地址" has-feedback prop="address">
          <a-input v-model="formModel.address" placeholder="请输入详细地址" />
        </a-form-model-item>
        <a-form-model-item label="坐标" prop="coordinate" help="用逗号分割, 例子:34.819159,113.630390">
          <div class="flex">
            <a-input v-model="formModel.coordinate" @blur="autoSortCoordinate" style="flex: 1; margin-right: 10px" />
            <a-button type="primary" @click="onClickSelectMap"> 选择 </a-button>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal title="选择用户" style="width: 300px" v-model="visible" :destroyOnClose="true" :footer="null">
      <div style="margin-bottom: 10px">
        <a-input-search placeholder="输入昵称搜索" v-model="keyword" allowClear enter-button @search="onSearch" />
      </div>
      <s-table ref="table1" rowKey="id" :columns="userColumns" :data="loadUserData">
        <span slot="baseinfo" slot-scope="text, record">
          <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
          <span :length="20" tooltip>{{ record.name }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onSelect(record)"> 选择 </a-button>
        </span>
        <span slot="status" slot-scope="scope">
          <div class="status">
            <span :class="scope.is_disable == 0 ? 'open' : 'close'"></span>
            <span>{{ scope.is_disable == 0 ? '已启用' : '已禁用' }}</span>
          </div>
        </span>
      </s-table>
    </a-modal>

    <SelectMap
      :oldmarker="formModel.coordinate"
      v-if="mapVisiable"
      :value.sync="mapVisiable"
      @onOk="selectMapOk"
    ></SelectMap>
  </page-header-wrapper>
</template>

<script>
import { Address } from '@/components'
import storage from 'store'
import { getSelectUserList } from '@/api/user'
import { STable } from '@/components'
import moment from 'moment'
import { getAdminListBySaas, editPasswordBySaas, deleteAdmin, editAdminBySaas, changeAgencyStatus } from '@/api/auth'
import { generateTokenByBdAgent } from '@/api/daili'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import SelectMap from '@/components/SelectMap/SelectMap'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '账户',
    dataIndex: 'username',
  },
  {
    title: '昵称',
    dataIndex: 'name',
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
  },
  {
    title: '可创建小程序',
    dataIndex: 'max_app_count',
    sorter: (a, b) => a.max_app_count - b.max_app_count,
  },
  {
    title: '剩余创建次数',
    dataIndex: 'last_count',
    sorter: (a, b) => a.last_count - b.last_count,
  },
  {
    title: '有效期',
    dataIndex: 'expire_time',
    scopedSlots: {
      customRender: 'expire_time',
    },
  },
  {
    title: '状态',
    dataIndex: 'is_enable',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '代理类型',
    dataIndex: 'area_level',
    scopedSlots: {
      customRender: 'area_level',
    },
  },
  {
    title: '备注',
    dataIndex: 'remark',
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

const userColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '用户信息',
    scopedSlots: { customRender: 'baseinfo' },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'AdminList',
  components: {
    STable,
    Address,
    SelectMap,
  },
  data() {
    return {
      // 地区信息
      addressInfo: {},
      userColumns,
      keyword: '',
      columns,
      visible: false,
      visibleEditPassword: false,
      admin: null,
      newPassword: '',
      confirmLoading: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      isNew: false,
      visibleCreate: false,
      formModel: {
        type: 3,
        area: {},
        area_level: 0,
        id: '',
        username: '',
        is_enable: '1',
        password: '',
        mobile: '',
        remark: '',
        name: '',
        max_app_count: 1,
        expire_time: 0,
        expire_time_always: true,
        saas_user_id: 0,
        // max_price: 0,
        rate: '',
        address: '',
        coordinate: '',
      },
      saas_user_name: '',
      queryParam: {
        name: '',
        mobile: '',
        status: '-1',
        user_name: '',
        area_level: '-1',
        type: 3,
      },
      rules: {
        username: [{ required: true, message: '请输入账户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        coordinate: [{ required: true, message: '请输入或选择坐标', trigger: 'blur' }],
      },
      loadUserData: (parameter) => {
        return getSelectUserList({
          ...parameter,
          storeId: storage.get('storeId'),
          type: 'user',
          keyword: this.keyword,
          ...this.queryParam,
        }).then((res) => {
          return res.data
        })
      },

      mapVisiable: false,
    }
  },
  watch: {
    visibleCreate: function (val) {
      if (!val) {
        setTimeout(() => {
          this.formModel = {
            type: 3,
            area: {},
            area_level: 0,
            id: '',
            username: '',
            is_enable: '1',
            password: '',
            mobile: '',
            remark: '',
            name: '',
            max_app_count: 1,
            expire_time: 0,
            expire_time_always: true,
            saas_user_id: 0,
            // max_price: 0,
            rate: '',
            address: '',
          }
          this.$refs['modelForm'].resetFields()
        }, 500)
      }
    },
  },
  computed: {
    area_level() {
      return function (area_level) {
        if (parseInt(area_level) === 0) {
          return '无'
        }
        if (parseInt(area_level) === 1) {
          return '区'
        }
        if (parseInt(area_level) === 2) {
          return '市'
        }
        if (parseInt(area_level) === 3) {
          return '省'
        }
      }
    },
  },
  created() {},
  methods: {
    onInStore: function (item) {
      generateTokenByBdAgent({ admin_id: item.id, username: item.username })
        .then((res) => {
          if (res.code == 0) {
            storage.set(ACCESS_TOKEN, res.data.access_token, 7 * 24 * 60 * 60 * 1000)
            this.$store.commit('SET_TOKEN', res.data.access_token)
            storage.set('isSaas', res.data.is_saas)
            storage.set('isSaasStore', false)
            storage.set('storeId', '')
            storage.set('daili', true)
            storage.remove('isPlatform')
            storage.remove('isSupplier')
            window.location.href = '/'
          } else {
            this.$message.error('获取token失败')
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {})
    },

    closeModel() {
      this.formModel.username = ''
      this.formModel.is_enable = '1'
      this.formModel.mobile = ''
      this.formModel.password = ''
      this.formModel.rate = ''
      this.formModel.name = ''
      this.formModel.max_app_count = '1'
      this.formModel.saas_user_id = ''
      this.formModel.expire_time_always = true
      this.formModel.expire_time = ''
      this.formModel.address = ''
      this.saas_user_name = ''
    },
    loadData(parameter) {
      let { queryParam: data } = this

      return getAdminListBySaas({ ...parameter, ...data })
        .then((res) => {
          return res.data
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.$refs.table.localLoading = false
        })
    },
    onEditPassword: function (admin) {
      this.admin = admin
      this.newPassword = ''
      this.visibleEditPassword = true
    },
    onEditPasswordOk: function () {
      if (this.newPassword == '') {
        this.$message.warning('请输入新密码')
        return
      }
      this.confirmLoading = true
      editPasswordBySaas({
        id: this.admin.id,
        password: this.newPassword,
      })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.visibleEditPassword = false
          } else {
            this.$message.warning(res.msg)
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {
          this.confirmLoading = false
        })
    },
    handleDelete: function (admin) {
      this.$message.loading({ content: '处理中...', key: 'deleteLoading' })
      deleteAdmin({ id: admin.id }).then((res) => {
        if (res.code == 0) {
          this.$refs.table.refresh(true)
          this.$message.success({ content: res.msg, key: 'deleteLoading' })
        } else {
          this.$message.warning({ content: res.msg, key: 'deleteLoading' })
        }
      })
    },
    onCreateOk() {
      this.$refs['modelForm'].validate((valid) => {
        if (valid) {
          const formModel = Object.assign({}, this.formModel)
          formModel.expire_time = moment(formModel.expire_time).format('YYYY-MM-DD')
          formModel.coordinate = formModel.coordinate.split(',')
          formModel.lng = formModel.coordinate[1]
          formModel.lat = formModel.coordinate[0]
          delete formModel.coordinate
          this.confirmLoading = true
          editAdminBySaas(formModel)
            .then((res) => {
              if (res.code == 0) {
                this.visibleCreate = false
                this.$message.success(res.msg)
                this.$refs.table.refresh(true)
              } else {
                this.$message.warning(res.msg)
              }
            })
            .catch((error) => {
              console.log(error)
            })
            .then(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleEdit(admin) {
      this.formModel.id = admin.id
      this.formModel.username = admin.username
      this.formModel.is_enable = admin.is_enable
      this.formModel.mobile = admin.mobile
      this.formModel.password = admin.password
      this.formModel.rate = admin.rate
      this.formModel.name = admin.name
      this.formModel.max_app_count = admin.max_app_count
      this.formModel.saas_user_id = admin.saas_user_id
      this.formModel.expire_time_always = admin.expire_time_always
      this.formModel.expire_time = admin.expire_time
      this.saas_user_name = admin.saas_user_name
      this.formModel.area = admin.area
      this.formModel.area_level = admin.area_level
      this.formModel.address = admin.address
      if (admin.lng && admin.lat) {
        this.formModel.coordinate = `${admin.lat},${admin.lng}`
      } else {
        this.formModel.coordinate = ''
      }

      if (admin.expire_time == '0') {
        this.formModel.expire_time = 0
        this.formModel.expire_time_always = true
      } else {
        this.formModel.expire_time_always = false
        this.formModel.expire_time = moment.unix(this.formModel.expire_time)
      }
      this.visibleCreate = true
    },
    onAdd() {
      this.isNew = true
      this.formModel = JSON.parse(JSON.stringify(defaultModel))
      this.visibleCreate = true
    },
    onCheckedChange(e) {
      if (e.target.checked) {
        this.formModel.expire_time_always = true
        this.formModel.expire_time = 0
      } else {
        this.formModel.expire_time_always = false
        this.formModel.expire_time = moment()
      }
    },
    onSelect(item) {
      this.formModel.saas_user_id = item.id
      this.saas_user_name = item.name
      this.visible = false
    },
    onSearch() {
      this.$refs.table1.refresh(true)
    },
    // 修改禁用状态
    async changeStatus(record, is_enable) {
      let param = { id: record.id, is_enable }
      const res = await changeAgencyStatus(param)
      if (res.code == 0) {
        this.$refs.table.refresh(true)
        this.$message.success('操作成功')
      }
    },

    autoSortCoordinate() {
      this.formModel.coordinate = this.formModel.coordinate.replace(/，/, ',')
      if (this.formModel.coordinate.indexOf(',') !== -1) {
        this.formModel.coordinate = this.formModel.coordinate
          .split(',')
          .sort((v1, v2) => {
            return v1 - v2
          })
          .toString()
      }
    },

    onClickSelectMap: function () {
      this.mapVisiable = true
    },

    selectMapOk(e) {
      this.formModel.coordinate = e
    },
  },
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}

.status {
  display: flex;
  align-items: center;
  span:nth-child(1) {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 4px;
  }
  .close {
    background-color: #ff4400;
  }
  .disabled {
    background-color: #ccc;
  }
  .open {
    background-color: #65c817;
  }
}

.flex {
  display: flex;
}
</style>
